<template>
  <div class="update-avatar">
    <img id="image" :src="imgUrl" />
    <div class="toolbar">
      <span @click="$emit('close-popup')">取消</span>
      <span @click="onConfirm">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { saveAvatar } from '@/api/user.js'
export default {
  data () {
    return {

    }
  },

  props: {
    imgUrl: {
      type: String,
      required: true
    }
  },

  created () {

  },

  mounted () {
    const image = document.getElementById('image')
    this.cropper = new Cropper(image, {
      aspectRatio: 1,
      dragMode: 'move', // 可拖拽
      cropBoxMovable: false, // 裁剪框不可移动
      background: false, // 去除格子背景
      viewMode: 1, // 图片在裁剪区内
      autoCropArea: 1, // 裁剪区域自动 默认最大裁剪区
      cropBoxResizable: false // 禁止裁剪区缩放
    })
  },

  methods: {
    // 点击完成
    onConfirm () {
      // 服务端裁剪
      // console.log(this.cropper.getData())
      // 客户端裁剪
      // this.cropper.getCroppedCanvas() 画布 将裁剪区域的图像画到了该画布上
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        // 创建一个表单数据
        const formData = new FormData()
        // 添加一个key为photo的表单数据
        formData.append('photo', blob)
        try {
          const res = await saveAvatar(formData)
          console.log(res)
          this.$toast.success('裁剪成功')
          this.$emit('close-popup')
          this.$emit('onUploadSuccess', res.data.data.photo)
        } catch (err) {
          this.$toast('裁剪失败')
        }
      })
    }
  }
}
</script>

<style scoped lang='less'>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
